package com.zhenghaijin.animecontentservice.service.impl;

import com.zhenghaijin.animecontentservice.mapper.AnimeMapper;
import com.zhenghaijin.animecontentservice.model.Anime;
import com.zhenghaijin.animecontentservice.service.AnimeService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Slf4j
@Service
public class AnimeServiceImpl implements AnimeService {

    private final AnimeMapper animeMapper;

    public AnimeServiceImpl(AnimeMapper animeMapper) {
        this.animeMapper = animeMapper;
    }

    @Override
    public List<Anime> getAllAnimes() {
        return animeMapper.findAll();
    }

    @Override
    public Anime getAnimeById(Long id) {
        Assert.notNull(id, "动漫ID不能为空：Anime ID must not be null");
        return animeMapper.findById(id);
    }

    @Override
    public int addAnime(Anime anime) {
        validateAnime(anime);
        int result = animeMapper.insert(anime);
        if (result > 0) {
            log.info("新增新动漫：Added new anime: {}", anime.getTitle());
        }
        return result;
    }

    @Override
    public int updateAnime(Anime anime) {
        validateAnime(anime);
        Assert.notNull(anime.getId(), "更新操作动漫ID不能为空：Anime ID must not be null for update");
        int result = animeMapper.update(anime);
        if (result == 0) {
            log.warn("Update failed for anime ID: {}", anime.getId());
            throw new RuntimeException("更新操作失败：Update operation failed");
        }
        return result;
    }

    @Override
    public int deleteAnime(Long id) {
        Assert.notNull(id, "动漫ID不能为空：Anime ID must not be null");
        int result = animeMapper.delete(id);
        if (result == 0) {
            log.error("删除操作失败：Delete failed for anime ID: {}", id);
            throw new RuntimeException("删除操作失败：Delete operation failed");
        }
        return result;
    }

    private void validateAnime(Anime anime) {
        Assert.notNull(anime, "动漫ID不能为空：Anime must not be null");
        Assert.hasText(anime.getTitle(), "动漫标题不能为空：Title must not be empty");
    }
}